package cn.hy.nio.example;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class Client {

    public static void main(String[] args) throws Exception {

        SocketChannel socketChannel = SocketChannel.open();

        // socketChannel.connect(new InetSocketAddress("localhost",8080));
        socketChannel.connect(new InetSocketAddress("localhost",8081));

        ByteBuffer buffer = ByteBuffer.wrap("1234".getBytes(StandardCharsets.UTF_8));

        socketChannel.write(buffer);
        int num;
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        while ( (num = socketChannel.read(readBuffer)) > 0) {
            readBuffer.flip();
            byte[] be = new byte[num];
            readBuffer.get(be);

            String result = new String(be, "UTF-8");
            System.out.println("返回值: " + result);
        }

    }
}
